
import Config from '../config';
import util from './common';
import { ErrorType } from '../types/index';

// 验证 token 是否失效
const checkTokenInvalid = () => {
  // token 存在并且在有效时间内 
  return my.getStorageSync({key: 'token'}).data;
}
// 设置请求头
const setRequestHeaders = (isToken = false) => {
  const requestHeader = {
    'Content-Type': 'application/json',
  };
  if (isToken) {
    const token = checkTokenInvalid();
    if (token) {
      requestHeader['Authorization'] = `Bearer ${token}`;
    }
    return { requestHeader, token };
  }
  return { requestHeader };
}
// 是否展示弹窗
const handleIsShow = (isShowToast) => {
  if (isShowToast) {
    my.showModal({
      content: '您目前没有登录，请先去登录',
      success: (res) => {
        if (res.confirm) {
          my.navigateTo({
            url: '/pages/login/login'
          });
        }
      }
    });
  } else {
    my.removeStorageSync({key: 'user'});
    my.removeStorageSync({key: 'token'});
  }
}

// API 请求
const request = (url, method: "GET" | "POST" | "PUT" | "DELETE" | "OPTIONS" | "HEAD" | "TRACE" | "CONNECT" = "GET", params = {}, isToken=false, isShowToast=true) => {  
  return new Promise(function (resolve, reject) {
    const { requestHeader, token } = setRequestHeaders(isToken);
    // 如果需要 token 并且获取失败
    if (isToken && !token) {
      handleIsShow(isShowToast);
      return reject('Token invalid');
    }
    my.request({
      url: Config.BLOG_HOST + url,
      data: params,
      method: method,
      headers: requestHeader,
      success: function (res) {
        if (res.statusCode == 200 || res.statusCode == 201) {
          resolve(res.data);
        } else {
          // 请求的页码大于总页数 不弹窗
          if ((res.data as Record<string, string>).code != 'rest_post_invalid_page_number' && isShowToast) {
            util.showToast((res.data as Record<string, string>).message || '请求失败')
          }
          // 获取个人信息，未登录或验证失效的情况，清空本地缓存
          if (!isShowToast) {
            console.log('清空');
            handleIsShow(false);
          }
          reject(res.data);
        }
      },
      fail: function (err: ErrorType) {
        util.showToast(err.data.message || '请求失败');
        reject(err);
      }
    })
  })
}
const get = (url, params = {}, isToken = false, isShowToast = true) => {
  return request(url, "GET", params, isToken, isShowToast);
}
const post = (url, params = {}, isToken = false) => {
  return request(url, "POST", params, isToken);
}
const uploadFile = (url, file) => {
  return new Promise(function (resolve, reject) {
    my.uploadFile({
      url: Config.BLOG_HOST + url,
      filePath: file.path,
      fileType: 'image',
      name: 'file',
      header: {
        'Authorization': `Bearer ${checkTokenInvalid()}`, 
        'Content-Type': 'multipart/form-data'
      },
      success (res){
        console.log("上传成功:", res);
        const data = JSON.parse(res.data);
        resolve(data.source_url); 
      },
      fail(err) {
        reject(err);
        console.error("上传失败:", err);
      }
    })
  }) 
}
export default {
  get,
  post,
  uploadFile
}
